package org.ellisande.grid.tags;

import javax.servlet.jsp.JspWriter;

import org.apache.commons.lang3.StringUtils;
import org.ellisande.grid.tags.support.TagBuilder;
import org.ellisande.tld.annotations.Attribute;
import org.ellisande.tld.annotations.Description;
import org.ellisande.tld.annotations.Info;
import org.ellisande.tld.annotations.Tag;

@Tag
@Info("Tag for adding checkboxes to the page")
public class CheckboxTag extends InputTag {

	private static final long serialVersionUID = -4940084105111716287L;

	@Attribute
	@Description("Defines whether or not this check box should be checked by default. Allowed values: true | false. Default value: false")
	private boolean checked = false;

	@Attribute 
	@Description("Defines a label for this checkbox. Default is no label.")
	private String label = null;

	private TagBuilder input = createInputTagBuilder();
	private TagBuilder boxLabel = createTagBuilder("label");

	private static final String LABLE_STYLE = "checkbox";

	@Override
	public void startTag() throws Exception {
		boxLabel.addStyle(LABLE_STYLE);
		input.addAttribute("type", "checkbox");
		if (checked) {
			input.addAttribute("checked", "checked");
		}

		JspWriter out = pageContext.getOut();
		if (label != null && !label.isEmpty()) {
			out.write(boxLabel.compileStartTag());
		}
		out.write(input.compileStartTag());

	}

	@Override
	public void endTag() throws Exception {
		JspWriter out = pageContext.getOut();
		if (!StringUtils.isEmpty(label)) {
			out.write(label);
			out.write(boxLabel.compileEndTag());
		}

	}

	@Override
	public void release() {
		super.release();
		input = null;
		boxLabel = null;
		label = null;
		checked = false;
	}

	public void setChecked(String checked) {
		this.checked = Boolean.parseBoolean(checked);
	}

	public void setLabel(String label) {
		this.label = label;
	}

}
